/**
 * 对话详情页面组件
 * 
 * 功能特性：
 * - 对话信息展示
 * - 消息历史记录
 * - 实时消息收发
 * - 对话状态管理
 * - 导出和分享功能
 * - 智能体性能分析
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect, useRef } from 'react';
import { 
  Card, 
  Descriptions, 
  Tag, 
  Button, 
  Space, 
  message, 
  Tabs,
  Spin,
  Alert,
  List,
  Typography,
  Input,
  Avatar,
  Tooltip,
  Badge,
  Statistic,
  Row,
  Col,
  Divider,
  Dropdown,
  Menu
} from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { 
  ArrowLeftOutlined, 
  EditOutlined, 
  DeleteOutlined,
  ReloadOutlined,
  SendOutlined,
  ExportOutlined,
  ShareAltOutlined,
  StopOutlined,
  RedoOutlined,
  CopyOutlined,
  DownloadOutlined,
  EyeOutlined,
  MessageOutlined,
  UserOutlined,
  RobotOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import conversationService, { ConversationStatus, ConversationMessageRole, ConversationMessageDto } from '@services/conversationService';
import agentService from '@services/agentService';

const { TextArea } = Input;
const { Text, Paragraph } = Typography;

interface Message {
  id: string;
  conversationId: string;
  role: ConversationMessageRole;
  content: string;
  timestamp: string;
  tokenCount?: number;
  cost?: number;
  metadata?: any;
}

interface Conversation {
  id: string;
  title: string;
  description: string;
  status: ConversationStatus;
  agentId: string;
  agentName?: string;
  messageCount: number;
  isActive: boolean;
  tags: string[];
  createdAt: string;
  updatedAt?: string;
  lastMessageAt?: string;
}

const ConversationDetail: React.FC = () => {
  const [conversation, setConversation] = useState<Conversation | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [messageLoading, setMessageLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [newMessage, setNewMessage] = useState('');
  const [sending, setSending] = useState(false);
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (id) {
      loadConversation();
      loadMessages();
    }
  }, [id]);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const loadConversation = async () => {
    if (!id) return;

    try {
      setLoading(true);
      setError(null);
      const response = await conversationService.getConversation(id);
      setConversation(response);
    } catch (err) {
      setError('加载对话详情失败');
      console.error('Conversation detail loading error:', err);
    } finally {
      setLoading(false);
    }
  };

  const loadMessages = async () => {
    if (!id) return;

    try {
      setMessageLoading(true);
      const response = await conversationService.getConversationMessages(id);
      // 将 ConversationMessageDto 转换为 Message 类型
      const messageArray: ConversationMessageDto[] = Array.isArray(response) ? response : response;
      const convertedMessages: Message[] = messageArray.map((msg: ConversationMessageDto) => ({
        id: msg.id,
        conversationId: msg.conversationId,
        role: msg.role,
        content: msg.content,
        timestamp: msg.createdAt,
        tokenCount: 0,
        cost: 0,
        metadata: msg.metadata
      }));
      setMessages(convertedMessages);
    } catch (err) {
      console.error('Messages loading error:', err);
      setMessages([]);
    } finally {
      setMessageLoading(false);
    }
  };

  const handleSendMessage = async () => {
    if (!newMessage.trim() || !id) return;

    try {
      setSending(true);
      await conversationService.sendMessage(id, {
        content: newMessage,
        role: ConversationMessageRole.User
      });

      setNewMessage('');
      loadMessages();
      loadConversation(); // 更新对话统计
    } catch (error) {
      message.error('发送消息失败');
    } finally {
      setSending(false);
    }
  };

  const handleClose = async () => {
    if (!id) return;
    
    try {
      await conversationService.closeConversation(id);
      message.success('对话已关闭');
      loadConversation();
    } catch (error) {
      message.error('关闭对话失败');
    }
  };

  const handleReopen = async () => {
    if (!id) return;
    
    try {
      await conversationService.reopenConversation(id);
      message.success('对话已重新打开');
      loadConversation();
    } catch (error) {
      message.error('重新打开对话失败');
    }
  };

  const handleDelete = async () => {
    if (!id) return;
    
    try {
      await conversationService.deleteConversation(id);
      message.success('删除成功');
      navigate('/conversations');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleExport = async (format: 'json' | 'txt' | 'markdown') => {
    if (!id) return;
    
    try {
      const data = {
        conversation,
        messages,
        exportFormat: format,
        exportedAt: new Date().toISOString()
      };
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { 
        type: 'application/json' 
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `conversation-${id}.${format}`;
      a.click();
      URL.revokeObjectURL(url);
      
      message.success(`导出为${format.toUpperCase()}格式成功`);
    } catch (error) {
      message.error('导出失败');
    }
  };

  const getStatusColor = (status: ConversationStatus) => {
    const colors = {
      [ConversationStatus.Active]: 'green',
      [ConversationStatus.Closed]: 'red',
      [ConversationStatus.Deleted]: 'gray',
      [ConversationStatus.Archived]: 'gray'
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  const getStatusText = (status: ConversationStatus) => {
    const texts = {
      [ConversationStatus.Active]: '进行中',
      [ConversationStatus.Closed]: '已关闭',
      [ConversationStatus.Deleted]: '已删除',
      [ConversationStatus.Archived]: '已归档'
    };
    return texts[status as keyof typeof texts] || '未知';
  };

  const formatMessageTime = (timestamp: string) => {
    return new Date(timestamp).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const renderMessage = (message: Message) => {
    const isUser = message.role === ConversationMessageRole.User;
    const isSystem = message.role === ConversationMessageRole.System;
    
    return (
      <div
        key={message.id}
        style={{
          display: 'flex',
          justifyContent: isUser ? 'flex-end' : 'flex-start',
          marginBottom: 16
        }}
      >
        {!isUser && (
          <Avatar 
            icon={isSystem ? <RobotOutlined /> : <UserOutlined />} 
            style={{ marginRight: 8, flexShrink: 0 }}
          />
        )}
        
        <div
          style={{
            maxWidth: '70%',
            background: isUser ? '#1890ff' : (isSystem ? '#f5f5f5' : '#f0f0f0'),
            color: isUser ? 'white' : 'black',
            padding: '12px 16px',
            borderRadius: 16,
            borderBottomLeftRadius: isUser ? 16 : 4,
            borderBottomRightRadius: isUser ? 4 : 16,
            boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
          }}
        >
          <div style={{ fontSize: '12px', marginBottom: 4, opacity: 0.8 }}>
            {isUser ? '我' : (isSystem ? '系统' : conversation?.agentName || '智能体')} 
            {' · '}
            {formatMessageTime(message.timestamp)}
          </div>
          <div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
            {message.content}
          </div>
          {message.tokenCount && (
            <div style={{ fontSize: '11px', marginTop: 4, opacity: 0.6 }}>
              {message.tokenCount} tokens
              {message.cost && ` · $${message.cost.toFixed(4)}`}
            </div>
          )}
        </div>
        
        {isUser && (
          <Avatar 
            icon={<UserOutlined />} 
            style={{ marginLeft: 8, flexShrink: 0 }}
          />
        )}
      </div>
    );
  };

  const exportMenu = (
    <Menu>
      <Menu.Item 
        key="json" 
        icon={<DownloadOutlined />}
        onClick={() => handleExport('json')}
      >
        导出为 JSON
      </Menu.Item>
      <Menu.Item 
        key="txt" 
        icon={<DownloadOutlined />}
        onClick={() => handleExport('txt')}
      >
        导出为 TXT
      </Menu.Item>
      <Menu.Item 
        key="markdown" 
        icon={<DownloadOutlined />}
        onClick={() => handleExport('markdown')}
      >
        导出为 Markdown
      </Menu.Item>
    </Menu>
  );

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error || !conversation) {
    return (
      <Alert
        message="错误"
        description={error || '对话不存在'}
        type="error"
        showIcon
        style={{ marginBottom: 24 }}
      />
    );
  }

  const canSendMessage = conversation.status === ConversationStatus.Active && conversation.isActive;

  return (
    <div>
      <Card
        title="对话详情"
        extra={
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/conversations')}>
              返回列表
            </Button>
            
            <Button icon={<ReloadOutlined />} onClick={loadConversation} loading={loading}>
              刷新
            </Button>
            
            <Button 
              icon={<EditOutlined />} 
              onClick={() => navigate(`/conversations/${id}/edit`)}
            >
              编辑
            </Button>
            
            <Dropdown overlay={exportMenu} placement="bottomRight">
              <Button icon={<ExportOutlined />}>
                导出 <CopyOutlined />
              </Button>
            </Dropdown>
            
            {conversation.status === ConversationStatus.Active ? (
              <Button 
                type="primary" 
                danger
                icon={<StopOutlined />}
                onClick={handleClose}
              >
                关闭对话
              </Button>
            ) : (
              <Button 
                type="primary" 
                icon={<RedoOutlined />}
                onClick={handleReopen}
              >
                重新打开
              </Button>
            )}
            
            <Button 
              danger 
              icon={<DeleteOutlined />}
              onClick={handleDelete}
            >
              删除
            </Button>
          </Space>
        }
      >
        {/* 对话基本信息 */}
        <Descriptions bordered column={2}>
          <Descriptions.Item label="标题">{conversation.title}</Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={getStatusColor(conversation.status)}>
              {getStatusText(conversation.status)}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="智能体">
            <Tag color="blue">
              {conversation.agentName || '未知智能体'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="激活状态">
            <Badge status={conversation.isActive ? 'success' : 'default'} 
              text={conversation.isActive ? '激活' : '停用'} />
          </Descriptions.Item>
          <Descriptions.Item label="消息数">
            <Badge count={conversation.messageCount} showZero color="#52c41a" />
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {new Date(conversation.createdAt).toLocaleString()}
          </Descriptions.Item>
          <Descriptions.Item label="最后消息时间" span={2}>
            {conversation.lastMessageAt ? 
              new Date(conversation.lastMessageAt).toLocaleString() : '无'
            }
          </Descriptions.Item>
          <Descriptions.Item label="描述" span={3}>
            {conversation.description}
          </Descriptions.Item>
          {conversation.tags.length > 0 && (
            <Descriptions.Item label="标签" span={3}>
              <Space size="small" wrap>
                {conversation.tags.map((tag, index) => (
                  <Tag key={index} color="purple">
                    {tag}
                  </Tag>
                ))}
              </Space>
            </Descriptions.Item>
          )}
        </Descriptions>

        {/* 详细信息标签页 */}
        <Card title="详细信息" style={{ marginTop: 16 }}>
          <Tabs
            defaultActiveKey="messages"
            items={[
              {
                key: 'messages',
                label: (
                  <span>
                    <MessageOutlined />
                    消息记录 ({messages.length})
                  </span>
                ),
                children: (
                  <>
                    {/* 消息列表 */}
                    <div
                      style={{
                        height: 500,
                        overflowY: 'auto',
                        padding: '16px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8
                      }}
                    >
                      {messageLoading ? (
                        <div style={{ textAlign: 'center', padding: '50px' }}>
                          <Spin />
                        </div>
                      ) : messages.length === 0 ? (
                        <div style={{ textAlign: 'center', padding: '50px', color: '#999' }}>
                          暂无消息记录
                        </div>
                      ) : (
                        <>
                          {messages.map(renderMessage)}
                          <div ref={messagesEndRef} />
                        </>
                      )}
                    </div>

                    {/* 消息输入区域 */}
                    {canSendMessage && (
                      <div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
                        <TextArea
                          value={newMessage}
                          onChange={(e) => setNewMessage(e.target.value)}
                          placeholder="输入消息..."
                          autoSize={{ minRows: 2, maxRows: 6 }}
                          onPressEnter={(e) => {
                            if (!e.shiftKey) {
                              e.preventDefault();
                              handleSendMessage();
                            }
                          }}
                        />
                        <Button
                          type="primary"
                          icon={<SendOutlined />}
                          onClick={handleSendMessage}
                          loading={sending}
                          disabled={!newMessage.trim()}
                        >
                          发送
                        </Button>
                      </div>
                    )}
                  </>
                )
              },
              {
                key: 'stats',
                label: (
                  <span>
                    <EyeOutlined />
                    统计分析
                  </span>
                ),
                children: (
                  <Row gutter={16}>
                    <Col span={6}>
                      <Card>
                        <Statistic
                          title="总消息数"
                          value={conversation.messageCount}
                          prefix={<MessageOutlined />}
                        />
                      </Card>
                    </Col>
                    <Col span={6}>
                      <Card>
                        <Statistic
                          title="用户消息"
                          value={messages.filter(m => m.role === ConversationMessageRole.User).length}
                          prefix={<UserOutlined />}
                        />
                      </Card>
                    </Col>
                    <Col span={6}>
                      <Card>
                        <Statistic
                          title="智能体回复"
                          value={messages.filter(m => m.role === ConversationMessageRole.Assistant).length}
                          prefix={<RobotOutlined />}
                        />
                      </Card>
                    </Col>
                    <Col span={6}>
                      <Card>
                        <Statistic
                          title="总Token消耗"
                          value={messages.reduce((sum, m) => sum + (m.tokenCount || 0), 0)}
                          prefix={<ClockCircleOutlined />}
                        />
                      </Card>
                    </Col>
                  </Row>
                )
              }
            ]}
          />
        </Card>
      </Card>
    </div>
  );
};

export default ConversationDetail;